<template>
    <div class="container mx-auto p-4">
      <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-900">用户管理</h1>
        <button
          @click="showCreateModal = true"
          class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
        >
          添加用户
        </button>
      </div>
  
      <!-- 用户列表 -->
      <div class="bg-white shadow rounded-lg overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">邮箱</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="user in users" :key="user.id">
              <td class="px-6 py-4 whitespace-nowrap text-gray-900">{{ user.id }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-gray-900">{{ user.email }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-gray-900">{{ formatDate(user.createdAt) }}</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <button
                  @click="editUser(user)"
                  class="text-blue-600 hover:text-blue-900 mr-4"
                >
                  编辑
                </button>
                <button
                  @click="deleteUser(user.id)"
                  class="text-red-600 hover:text-red-900"
                >
                  删除
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
  
      <!-- 创建/编辑用户模态框 -->
      <div v-if="showCreateModal || showEditModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
        <div class="bg-white p-6 rounded-lg w-full max-w-md">
          <h2 class="text-xl font-bold mb-4 text-gray-900">
            {{ showEditModal ? '编辑用户' : '创建用户' }}
          </h2>
          <form @submit.prevent="handleSubmit">
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700">邮箱</label>
              <input
                v-model="formData.email"
                type="email"
                required
                class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
              >
            </div>
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700">密码</label>
              <input
                v-model="formData.password"
                type="password"
                :required="!showEditModal"
                class="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:outline-none focus:ring-1 focus:ring-blue-500"
              >
              <p v-if="showEditModal" class="text-sm text-gray-500 mt-1">留空表示不修改密码</p>
            </div>
            <div class="flex justify-end space-x-4">
              <button
                type="button"
                @click="closeModal"
                class="px-4 py-2 border border-gray-300 rounded text-gray-700 bg-white hover:bg-gray-50"
              >
                取消
              </button>
              <button
                type="submit"
                class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
              >
                确定
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  const users = ref([])
  const showCreateModal = ref(false)
  const showEditModal = ref(false)
  const formData = ref({
    id: null,
    email: '',
    password: ''
  })
  
  // 获取用户列表
  const fetchUsers = async () => {
    try {
      const response = await $fetch('/api/users')
      users.value = response.users
    } catch (error) {
      console.error('获取用户列表失败:', error)
    }
  }
  
  // 格式化日期
  const formatDate = (date) => {
    return new Date(date).toLocaleString()
  }
  
  // 创建用户
  const createUser = async () => {
    try {
      await $fetch('/api/users', {
        method: 'POST',
        body: formData.value
      })
      await fetchUsers()
      closeModal()
    } catch (error) {
      console.error('创建用户失败:', error)
    }
  }
  
  // 编辑用户
  const editUser = (user) => {
    formData.value = {
      id: user.id,
      email: user.email,
      password: ''
    }
    showEditModal.value = true
  }
  
  // 更新用户
  const updateUser = async () => {
    try {
      await $fetch(`/api/users/${formData.value.id}`, {
        method: 'PUT',
        body: formData.value
      })
      await fetchUsers()
      closeModal()
    } catch (error) {
      console.error('更新用户失败:', error)
    }
  }
  
  // 删除用户
  const deleteUser = async (id) => {
    if (!confirm('确定要删除该用户吗？')) return
    
    try {
      await $fetch(`/api/users/${id}`, {
        method: 'DELETE'
      })
      await fetchUsers()
    } catch (error) {
      console.error('删除用户失败:', error)
    }
  }
  
  // 提交表单
  const handleSubmit = async () => {
    if (showEditModal.value) {
      await updateUser()
    } else {
      await createUser()
    }
  }
  
  // 关闭模态框
  const closeModal = () => {
    showCreateModal.value = false
    showEditModal.value = false
    formData.value = {
      id: null,
      email: '',
      password: ''
    }
  }
  
  // 页面加载时获取用户列表
  onMounted(() => {
    fetchUsers()
  })
  </script>